//
//  UIImage+Resize.m
//  SQB
//
//  Created by  tom on 10-1-11.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UIImage+Resize.h"

#define ORIGINAL_MAX_WIDTH ([UIScreen mainScreen].bounds.size.width)

@implementation UIImage (SQBUIImageResize)

- (UIImage *)sqb_imageByResizingToSize:(CGSize)targetSize
                   preserveAspectRatio:(BOOL)preserveAspectRatio
                             trimToFit:(BOOL)trimToFit {
	CGSize imageSize = [self size];
	if (imageSize.height < 1 || imageSize.width < 1) {
		return nil;
	}
	if (targetSize.height < 1 || targetSize.width < 1) {
		return nil;
	}
    
	CGFloat aspectRatio = imageSize.width / imageSize.height;
	CGFloat targetAspectRatio = targetSize.width / targetSize.height;
	CGRect projectTo = CGRectZero;
    if (aspectRatio == targetAspectRatio) {
        return self;
    }
	if (preserveAspectRatio) {
		if (trimToFit) {
			// Scale and clip image so that the aspect ratio is preserved and the
			// target size is filled.
			if (targetAspectRatio < aspectRatio) {
				// clip the x-axis.
				projectTo.size.width = targetSize.height * aspectRatio;
				projectTo.size.height = targetSize.height;
				projectTo.origin.x = (targetSize.width - projectTo.size.width) / 2;
				projectTo.origin.y = 0;
			} else {
				// clip the y-axis.
				projectTo.size.width = targetSize.width;
				projectTo.size.height = targetSize.width / aspectRatio;
				projectTo.origin.x = 0;
				projectTo.origin.y = (targetSize.height - projectTo.size.height) / 2;
			}
		} else {
			// Scale image to ensure it fits inside the specified targetSize.
			if (targetAspectRatio < aspectRatio) {
				// target is less wide than the original.
				projectTo.size.width = targetSize.width;
				projectTo.size.height = projectTo.size.width / aspectRatio;
				targetSize = projectTo.size;
			} else {
				// target is wider than the original.
				projectTo.size.height = targetSize.height;
				projectTo.size.width = projectTo.size.height * aspectRatio;
				targetSize = projectTo.size;
			}
		} // if (clip)
	} else {
		// Don't preserve the aspect ratio.
		projectTo.size = targetSize;
	}
	
	projectTo = CGRectIntegral(projectTo);
	// There's no CGSizeIntegral, so we fake our own.
	CGRect integralRect = CGRectZero;
	integralRect.size = targetSize;
	targetSize = CGRectIntegral(integralRect).size;
	
	// Resize photo. Use UIImage drawing methods because they respect
	// UIImageOrientation as opposed to CGContextDrawImage().
	//UIGraphicsBeginImageContext(targetSize);
    UIGraphicsBeginImageContextWithOptions(targetSize,NO,0.0);
	[self drawInRect:projectTo];
	UIImage* resizedPhoto = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return resizedPhoto;
}

- (UIImage *)sqb_imageByResizingToSize:(CGSize)targetSize
                            faceCenter:(CGPoint)faceCenter
{
    CGSize imageSize = [self size];
	if (imageSize.height < 1 || imageSize.width < 1) {
		return nil;
	}
	if (targetSize.height < 1 || targetSize.width < 1) {
		return nil;
	}
    
	CGFloat aspectRatio = imageSize.width / imageSize.height;
	CGFloat targetAspectRatio = targetSize.width / targetSize.height;
	CGRect projectTo = CGRectZero;
    if (aspectRatio == targetAspectRatio) {
        return self;
    }
    
    // Scale and clip image so that the aspect ratio is preserved and the
    // target size is filled.
    if (targetAspectRatio < aspectRatio) {
        // clip the x-axis.
        projectTo.size.width = targetSize.height * aspectRatio;
        projectTo.size.height = targetSize.height;
        projectTo.origin.x = faceCenter.x*targetSize.height/imageSize.height - targetSize.width/2;
        if (projectTo.origin.x < 0)
        {
            projectTo.origin.x = 0;
        }
        if (projectTo.origin.x > (targetSize.height*imageSize.width/imageSize.height - targetSize.width))
        {
            projectTo.origin.x = targetSize.height*imageSize.width/imageSize.height - targetSize.width;
        }
        projectTo.origin.x = -projectTo.origin.x;
        projectTo.origin.y = 0;
    } else {
        // clip the y-axis.
        projectTo.size.width = targetSize.width;
        projectTo.size.height = targetSize.width / aspectRatio;
        projectTo.origin.x = 0;
        projectTo.origin.y = faceCenter.y*targetSize.width/imageSize.width - targetSize.height/2;
        if (projectTo.origin.y < 0)
        {
            projectTo.origin.y = 0;
        }
        if (projectTo.origin.y > (targetSize.width/aspectRatio - targetSize.height))
        {
            projectTo.origin.y = targetSize.width/aspectRatio - targetSize.height;
        }
        projectTo.origin.y = -projectTo.origin.y;
    }
    
    projectTo = CGRectIntegral(projectTo);
	// There's no CGSizeIntegral, so we fake our own.
	CGRect integralRect = CGRectZero;
	integralRect.size = targetSize;
	targetSize = CGRectIntegral(integralRect).size;
	
	// Resize photo. Use UIImage drawing methods because they respect
	// UIImageOrientation as opposed to CGContextDrawImage().
	//UIGraphicsBeginImageContext(targetSize);
    UIGraphicsBeginImageContextWithOptions(targetSize,NO,0.0);
	[self drawInRect:projectTo];
	UIImage* resizedPhoto = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return resizedPhoto;
}

- (UIImage *)rotaImage{
    int w = self.size.width;
    int h = self.size.height;
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        //CGContextRotateCTM(context,M_PI);
        CGContextScaleCTM (context, -1, -1);
        CGContextTranslateCTM(context, -w,-h);
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), self.CGImage);
        
    }
    
    UIImage *mask = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  mask;
}

- (UIImage *)circleImage{
    int w = self.size.width;
    int h = self.size.height;
    UIBezierPath *path = nil;
    if(w>=h){
        path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake((w-h)/2, 0, h, h)];
    }else{
        path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, (h-w)/2, w, w)];
    }
    [path closePath];
    [path fill];
    
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        //CGContextRotateCTM(context,M_PI);
        CGContextScaleCTM (context, 1, -1);
        CGContextTranslateCTM(context, 0,-h);
        CGContextAddPath(context, path.CGPath);
        CGContextClosePath(context);
        CGContextClip(context);
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), self.CGImage);
        
    }
    
    
    
    
    UIImage *mask = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  mask;
}

- (UIImage *)imageByScalingToMaxSize
{
    if (self.size.width < ORIGINAL_MAX_WIDTH) return self;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (self.size.width > self.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = self.size.width * (ORIGINAL_MAX_WIDTH / self.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = self.size.height * (ORIGINAL_MAX_WIDTH / self.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:self targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end